/**
 * 核心工具，需添加工具请移步 src/utils
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { getRules as _getRules, RuleHandler } from 'lg.validator';
import messageUtils from './message';

export const message = messageUtils;
export * from './assert';
export * from './auth';
export * from './color';
export * from './data';
export * from './file';
export * from './format';
export * from './random';
export * from './api';
export * from './loader';
export * from './dom';

let RULES: RuleHandler = null;
function getRules(): RuleHandler {
  if (!RULES) {
    RULES = _getRules();
  }
  return RULES;
}

export const rules = {
  required(msg = '必填') {
    return [{ required: true, message: msg, trigger: 'blur' }];
  },
  idcard(msg = '请输入正确的身份证号码') {
    return [{ validator: (val: any) => getRules().idcard(val), message: msg, trigger: 'blur' }];
  },
  email(msg = '请输入正确的邮箱地址') {
    return [{ validator: (val: any) => getRules().email(val), message: msg, trigger: 'blur' }];
  },
  phone(msg = '请输入正确的手机号码') {
    return [{ validator: (val: any) => getRules().phone(val), message: msg, trigger: 'blur' }];
  },
  bankcard(msg = '请输入正确的银行卡号码') {
    return [{ validator: (val: any) => getRules().bankcard(val), message: msg, trigger: 'blur' }];
  },
  tel(msg = '请输入正确的电话号码') {
    return [{ validator: (val: any) => getRules().tel(val), message: msg, trigger: 'blur' }];
  },
  postcode(msg = '请输入正确的邮政编码') {
    return [{ validator: (val: any) => getRules().postcode(val), message: msg, trigger: 'blur' }];
  },
  url(msg = '请输入正确的网址') {
    return [{ validator: (val: any) => getRules().url(val), message: msg, trigger: 'blur' }];
  },
  ipv4(msg = '请输入正确的IP4') {
    return [{ validator: (val: any) => getRules().ipv4(val), message: msg, trigger: 'blur' }];
  },
  qq(msg = '请输入正确的QQ号码') {
    return [{ validator: (val: any) => getRules().qq(val), message: msg, trigger: 'blur' }];
  },
  number(msg = '只能输入数值') {
    return [{ validator: (val: any) => getRules().number(val), message: msg, trigger: 'blur' }];
  },
  digits(msg = '必须输入一个整数') {
    return [{ validator: (val: any) => getRules().digits(val), message: msg, trigger: 'blur' }];
  },
  decimal(msg = '必须输入一个小数') {
    return [{ validator: (val: any) => getRules().decimal(val), message: msg, trigger: 'blur' }];
  },
};

export function debounce(func, wait) {
  let timeout;
  return function (...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}
